package com.alphas.project.service.impl;

import com.alphas.project.common.ErrorCode;
import com.alphas.project.exception.BusinessException;
import com.alphas.project.model.entity.InterfaceInfo;
import com.alphas.project.model.enums.HttpMethodEnum;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.alphas.project.model.entity.UserInterfaceInfo;
import com.alphas.project.service.UserInterfaceInfoService;
import com.alphas.project.mapper.UserInterfaceInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @author 57450
 * @description 针对表【user_interface_info(用户调用接口关系表)】的数据库操作Service实现
 * @createDate 2025-02-10 11:48:02
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
        implements UserInterfaceInfoService {
    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean b) {

        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = userInterfaceInfo.getUserId();
        Long interfaceInfoId = userInterfaceInfo.getInterfaceInfoId();
        Integer totalNum = userInterfaceInfo.getTotalNum();
        Integer leftNum = userInterfaceInfo.getLeftNum();
        Integer status = userInterfaceInfo.getStatus();
        // 创建时，所有参数必须非空
        if (b) {
            if (userId <= 0 || interfaceInfoId <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口或用户不存在");
            }
            if (leftNum < 0 || totalNum < 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余次数或总次数小于0");
            }
            if (status != null && status != 0 && status != 1) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "状态值不合法");
            }
        }
    }

    @Override
    public boolean invokeCount(long interfaceInfoId, long userId) {
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UpdateWrapper<UserInterfaceInfo> userInterfaceInfoUpdateWrapper = new UpdateWrapper<>();
        userInterfaceInfoUpdateWrapper.eq("user_id", userId);
        userInterfaceInfoUpdateWrapper.eq("interface_info_id", interfaceInfoId);
        userInterfaceInfoUpdateWrapper.gt("left_num", 0);
        userInterfaceInfoUpdateWrapper.setSql("left_num = left_num - 1,total_num = total_num + 1");
        return this.update(userInterfaceInfoUpdateWrapper);
    }

}




